package com.golddaymicromall.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.golddaymicromall.adapter.ProductItemAdapter;
import com.golddaymicromall.application.MyApplication;
import com.golddaymicromall.base.BaseActivity;
import com.golddaymicromall.bean.LoginInfo;
import com.golddaymicromall.bean.ProductAllInfo;
import com.golddaymicromall.bean.ProductClassInfo;
import com.golddaymicromall.bean.UpdateInfo;
import com.golddaymicromall.jpush.JPushUtil;
import com.golddaymicromall.model.HttpModel;
import com.golddaymicromall.util.ActivityController;
import com.golddaymicromall.util.ApkUtils;
import com.golddaymicromall.util.Log;
import com.golddaymicromall.util.MD5;
import com.golddaymicromall.util.RopUtils;
import com.golddaymicromall.util.SPUtils;
import com.golddaymicromall.util.ServerConfig;
import com.golddaymicromall.view.Home_SlideShowView;
import com.google.common.collect.Maps;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.convert.FileConvert;
import com.lzy.okgo.convert.StringConvert;
import com.lzy.okrx.RxAdapter;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;

public class MainActivity extends BaseActivity {

    @Bind(R.id.home_slideshowView)
    Home_SlideShowView homeSlideshowView;
    @Bind(R.id.me_iv)
    TextView meIv;
    @Bind(R.id.me_ll)
    LinearLayout me_ll;
    @Bind(R.id.product_item)
    ListView productItem;
    @Bind(R.id.stby)
    TextView stby;
    @Bind(R.id.zxjkhl)
    TextView zxjkhl;
    @Bind(R.id.xyys)
    TextView xyys;
    @Bind(R.id.xltrhzp)
    TextView xltrhzp;
    @Bind(R.id.dptc)
    TextView dptc;
    @Bind(R.id.fxp)
    TextView fxp;
    @Bind(R.id.qt)
    TextView qt;
    @Bind(R.id.zyysxl)
    TextView zyysxl;
    @Bind(R.id.xlstby)
    TextView xlstby;
    @Bind(R.id.smcp)
    TextView smcp;
    @Bind(R.id.product_none)
    TextView product_none;

    ProgressDialog progressDialog;
    private UpdateInfo info;
    private List<ProductClassInfo> productinfo;
    ProductItemAdapter adapter;
    public static boolean isForeground = false;
    List<ProductAllInfo> list;
    String password;
    private int typeFlag = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        initData();
        init();
        registerMessageReceiver();
    }

    private void initData() {

        Intent intent = getIntent();
        if (null != intent.getExtras()) {
            Bundle bundle = getIntent().getExtras();
            String title = bundle.getString(JPushInterface.EXTRA_NOTIFICATION_TITLE);
            String content = bundle.getString(JPushInterface.EXTRA_ALERT);

            new AlertDialog.Builder(this)
                    .setIcon(R.mipmap.ic_launcher)
                    .setTitle(title)
                    .setMessage(content)
                    .setCancelable(false)
                    .setNegativeButton("关闭", null)
                    .show();

        }


        changeStyle(stby);
        attemptProductTypeInfo();
        attemptLogin();
        //检查更新
        checkUpdate();
    }

    @OnClick({R.id.me_ll, R.id.stby, R.id.zxjkhl, R.id.xyys, R.id.xltrhzp, R.id.dptc, R.id.fxp, R.id.qt, R.id.zyysxl, R.id.xlstby, R.id.smcp})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.me_ll:
                Intent toMe = new Intent(this, MeActivity.class);
                startActivity(toMe);
                break;
            case R.id.stby:
                changeStyle(stby);
                if (typeFlag == 1) {
                    attemptProductInfo(productinfo.get(1).getId());
                } else {
                    Toast.makeText(MainActivity.this, "正在加载，请稍后", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.zxjkhl:
                changeStyle(zxjkhl);
                if (typeFlag == 1) {
                    attemptProductInfo(productinfo.get(4).getId());
                } else {
                    Toast.makeText(MainActivity.this, "正在加载，请稍后", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.xyys:
                changeStyle(xyys);
                if (typeFlag == 1) {
                    attemptProductInfo(productinfo.get(5).getId());
                } else {
                    Toast.makeText(MainActivity.this, "正在加载，请稍后", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.xltrhzp:
                changeStyle(xltrhzp);
                if (typeFlag == 1) {
                    attemptProductInfo(productinfo.get(6).getId());
                } else {
                    Toast.makeText(MainActivity.this, "正在加载，请稍后", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.dptc:
                changeStyle(dptc);
                if (typeFlag == 1) {
                    attemptProductInfo(productinfo.get(0).getId());
                } else {
                    Toast.makeText(MainActivity.this, "正在加载，请稍后", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.fxp:
                changeStyle(fxp);
                if (typeFlag == 1) {
                    attemptProductInfo(productinfo.get(9).getId());
                } else {
                    Toast.makeText(MainActivity.this, "正在加载，请稍后", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.qt:
                changeStyle(qt);
                if (typeFlag == 1) {
                    attemptProductInfo(productinfo.get(3).getId());
                } else {
                    Toast.makeText(MainActivity.this, "正在加载，请稍后", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.zyysxl:
                changeStyle(zyysxl);
                if (typeFlag == 1) {
                    attemptProductInfo(productinfo.get(2).getId());
                } else {
                    Toast.makeText(MainActivity.this, "正在加载，请稍后", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.xlstby:
                changeStyle(xlstby);
                if (typeFlag == 1) {
                    attemptProductInfo(productinfo.get(8).getId());
                } else {
                    Toast.makeText(MainActivity.this, "正在加载，请稍后", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.smcp:
                changeStyle(smcp);
                if (typeFlag == 1) {
                    attemptProductInfo(productinfo.get(7).getId());
                } else {
                    Toast.makeText(MainActivity.this, "正在加载，请稍后", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    //设置产品类型的点击状态
    public void changeStyle(TextView tv) {
        //设置字体
        stby.setTextAppearance(this, R.style.productNormal);
        zxjkhl.setTextAppearance(this, R.style.productNormal);
        xyys.setTextAppearance(this, R.style.productNormal);
        xltrhzp.setTextAppearance(this, R.style.productNormal);
        dptc.setTextAppearance(this, R.style.productNormal);
        fxp.setTextAppearance(this, R.style.productNormal);
        qt.setTextAppearance(this, R.style.productNormal);
        zyysxl.setTextAppearance(this, R.style.productNormal);
        xlstby.setTextAppearance(this, R.style.productNormal);
        smcp.setTextAppearance(this, R.style.productNormal);
        //设置背景图片
        stby.setBackgroundResource(R.drawable.ic_none_xuanzhong);
        zxjkhl.setBackgroundResource(R.drawable.ic_none_xuanzhong);
        xyys.setBackgroundResource(R.drawable.ic_none_xuanzhong);
        xltrhzp.setBackgroundResource(R.drawable.ic_none_xuanzhong);
        dptc.setBackgroundResource(R.drawable.ic_none_xuanzhong);
        fxp.setBackgroundResource(R.drawable.ic_none_xuanzhong);
        qt.setBackgroundResource(R.drawable.ic_none_xuanzhong);
        zyysxl.setBackgroundResource(R.drawable.ic_none_xuanzhong);
        xlstby.setBackgroundResource(R.drawable.ic_none_xuanzhong);
        smcp.setBackgroundResource(R.drawable.ic_none_xuanzhong);

        tv.setTextAppearance(this, R.style.productBold);
        tv.setBackgroundResource(R.drawable.ic_xuanzhong);

    }

    //登录
    private void attemptLogin() {
        String customerNo = SPUtils.get(getApplicationContext(), "Customerno", "").toString();
        password = SPUtils.get(getApplicationContext(), "password1", "").toString();
        //获取设备ID
        String androidID = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
        final String token = MD5.md5(customerNo + androidID);

        Map<String, String> form = Maps.newHashMap();
        form.put("method", "rop.user.login");
        form.put("appKey", "00001");
        form.put("v", "1.0");
        form.put("format", "json");
        form.put("login", customerNo);
        form.put("phoneid", token + "Android");
        form.put("regist", password);
        String sing = RopUtils.signString(form, "qwertyuiop");
        form.put("sign", sing);

        OkGo.post(new ServerConfig().SERVER)
                .params(form)
                .getCall(StringConvert.create(), RxAdapter.<String>create())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(result -> {
                    if (!"".equals(result)) {
                        JSONObject jsonObject = JSON.parseObject(result);
                        if (result.contains("errorToken") || "0".equals(result) || "null".equals(result)) {
                            ActivityController.getInstance().finishActivity();
                            Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                        } else if ("失败".equals(jsonObject.get("active").toString())) {
                            //提示对话框
                            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                            builder.setTitle("提示").setMessage("您的账号已在其他设备登录，请在其他设备上退出再登录").setNegativeButton("确定", (dialog, which) -> {
                                // TODO Auto-generated method stub
                                dialog.dismiss();
                                ActivityController.getInstance().finishActivity();
                                Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                startActivity(intent);
                            }).show();
                        } else {
                            LoginInfo info = JSON.parseObject(result, LoginInfo.class);
                            SPUtils.put(MainActivity.this, "Token", token + "Android");
                            SPUtils.put(MainActivity.this, "Username", info.getUsername() == null ? "" : info.getUsername());
                            SPUtils.put(MainActivity.this, "Active", info.getActive() == null ? "" : info.getActive());
                            SPUtils.put(MainActivity.this, "Customerguid", info.getCustomerguid() == null ? "" : info.getCustomerguid());
                            SPUtils.put(MainActivity.this, "Customerno", info.getCustomerno() == null ? "" : info.getCustomerno());
                            SPUtils.put(MainActivity.this, "Email", info.getEmail() == null ? "" : info.getEmail());
                            SPUtils.put(MainActivity.this, "Id", info.getId() == null ? "" : info.getId());
                            SPUtils.put(MainActivity.this, "Lastlogindate", info.getLastlogindate() == null ? "" : info.getLastlogindate());
                            SPUtils.put(MainActivity.this, "OrganizationId", info.getOrganizationId() == null ? "" : info.getOrganizationId());
                            SPUtils.put(MainActivity.this, "Password", info.getPassword() == null ? "" : info.getPassword());
                            SPUtils.put(MainActivity.this, "password1", password);
                            SPUtils.put(MainActivity.this, "Status", info.getStatus() == null ? "" : info.getStatus());
                            SPUtils.put(MainActivity.this, "Trandword", info.getTrandword() == null ? "" : info.getTrandword());
                            SPUtils.put(MainActivity.this, "headImg", info.getImage() == null ? "" : info.getImage());
                            SPUtils.put(MainActivity.this, "deptFlag", info.getFlag() == null ? "" : info.getFlag());
                        }
                    } else {
                        ActivityController.getInstance().finishActivity();
                        Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                    }
                }, throwable -> {
                    showError();
                    throwable.printStackTrace();
                });
    }

    //获取产品类型信息
    private void attemptProductTypeInfo() {
        Map<String, String> form = Maps.newHashMap();
        form.put("method", "rop.productclass.get");
        form.put("appKey", "00001");
        form.put("v", "1.0");
        form.put("format", "json");
        String sing = RopUtils.signString(form, "qwertyuiop");
        form.put("sign", sing);

        OkGo.post(new ServerConfig().SERVER)
                .params(form)
                .getCall(StringConvert.create(), RxAdapter.<String>create())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(result -> {
                    productinfo = new ArrayList<ProductClassInfo>();
                    if (!"".equals(result)) {
                        if (result.contains("errorToken") || "0".equals(result)) {
                            Toast.makeText(MainActivity.this, "访问服务器失败,请稍后重试", Toast.LENGTH_SHORT).show();
                        } else if ("null".equals(result)) {
                            Toast.makeText(MainActivity.this, "暂无数据", Toast.LENGTH_SHORT).show();
                        } else {
                            productinfo = JSON.parseArray(result, ProductClassInfo.class);
                            if (productinfo.size() > 0) {
                                stby.setText(productinfo.get(1).getClassname());
                                zxjkhl.setText(productinfo.get(4).getClassname());
                                xyys.setText(productinfo.get(5).getClassname());
                                xltrhzp.setText(productinfo.get(6).getClassname());
                                dptc.setText(productinfo.get(0).getClassname());
                                fxp.setText(productinfo.get(9).getClassname());
                                qt.setText(productinfo.get(3).getClassname());
                                zyysxl.setText(productinfo.get(2).getClassname());
                                xlstby.setText(productinfo.get(8).getClassname());
                                smcp.setText(productinfo.get(7).getClassname());
                                attemptProductInfo(productinfo.get(1).getId());
                                Log.e("Id", productinfo.get(1).getId());
                                typeFlag = 1;
                            }
                        }
                    } else {
                        showError();
                    }
                }, throwable -> {
                    showError();
                    throwable.printStackTrace();
                });

    }

    //获取产品信息
    private void attemptProductInfo(String id) {
        Map<String, String> form = Maps.newHashMap();
        form.put("method", "rop.product.get");
        form.put("appKey", "00001");
        form.put("v", "1.0");
        form.put("format", "json");
        form.put("pcid", id);
        String sing = RopUtils.signString(form, "qwertyuiop");
        form.put("sign", sing);

        OkGo.post(new ServerConfig().SERVER)
                .params(form)
                .getCall(StringConvert.create(), RxAdapter.<String>create())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(result -> {
                    if (result != null) {
                        //在这里进行返回值的处理
                        if (result.contains("errorToken") || "0".equals(result)) {
                            Toast.makeText(getApplicationContext(), "访问服务器失败,请稍后重试", Toast.LENGTH_SHORT).show();
                        } else if ("null".equals(result)) {
                            Toast.makeText(getApplicationContext(), "暂无数据", Toast.LENGTH_SHORT).show();
                        } else {
                            list = JSON.parseArray(result, ProductAllInfo.class);
                            if (list.size() > 0) {
                                if (list.get(0).getResult() == null) {
                                    productItem.setVisibility(View.GONE);
                                    product_none.setVisibility(View.VISIBLE);
                                } else {
                                    if (list.get(0).getResult().size() > 0) {
                                        product_none.setVisibility(View.GONE);
                                        productItem.setVisibility(View.VISIBLE);
                                        adapter = new ProductItemAdapter(MainActivity.this, list.get(0).getResult());
                                        productItem.setAdapter(adapter);
                                    }
                                }
                            } else {
                                showError();
                            }
                        }
                    } else {
                        showError();
                    }
                }, throwable -> {
                    showError();
                    throwable.printStackTrace();
                });

    }

    //检查更新
    public void checkUpdate() {
        // 自动检查有没有新版本 如果有新版本就提示更新
        String path = new HttpModel().IMGURL + "update.txt";
        OkGo.post(path)
                .getCall(new StringConvert(), RxAdapter.<String>create())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(s -> {
                    String info = s.toString().replace("\r\n", "");
                    UpdateInfo updateInfo = new UpdateInfo();
                    updateInfo.setVersionName(info.split("&")[0]);
                    updateInfo.setVersion(info.split("&")[1]);
                    updateInfo.setDescription(info.split("&")[2]);
                    updateInfo.setUrl(info.split("&")[3]);
                    if (isNeedUpdate(updateInfo)) {
                        this.info = updateInfo;
                        showUpdateDialog();
                    }
                }, throwable -> {
                    throwable.printStackTrace();
                });
    }

    public boolean isNeedUpdate(UpdateInfo updateInfo) {
        String new_version = null;
        int now_version = 0;
        try {
            new_version = updateInfo.getVersion(); // 最新版本的版本号
            //获取当前版本号
            now_version = 0;
            PackageManager packageManager = this.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    this.getPackageName(), 0);
            now_version = packageInfo.versionCode;
            //new_version.equals(now_version)
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        if (Integer.parseInt(new_version) > now_version) {
            SPUtils.put(this, "update", "1");//有更新
            return true;
        } else {
            SPUtils.put(this, "update", "0");//无更新
            return false;
        }
    }

    public void deletePhoneId() {
        String ID = SPUtils.get(getApplicationContext(), "Id", "").toString();
        Map<String, String> form = Maps.newHashMap();
        form.put("method", "rop.user.updatephoneid");
        form.put("appKey", "00001");
        form.put("v", "1.0");
        form.put("format", "json");
        form.put("id", ID);
        String sing = RopUtils.signString(form, "qwertyuiop");
        form.put("sign", sing);

        OkGo.post(new ServerConfig().SERVER)
                .params(form)
                .getCall(StringConvert.create(), RxAdapter.<String>create())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(s -> {
                }, throwable -> {
                    throwable.printStackTrace();
                });
    }

    //显示是否要更新的对话框
    private void showUpdateDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setIcon(android.R.drawable.ic_dialog_info);
        builder.setCancelable(false);
        builder.setTitle("请升级APP至版本" + info.getVersionName());
        builder.setMessage(info.getDescription());
        builder.setPositiveButton("确定", (dialog, which) -> {
            deletePhoneId();
            if (Environment.getExternalStorageState().equals(
                    Environment.MEDIA_MOUNTED)) {
                downFile(info.getUrl());
            } else {
                Toast.makeText(MainActivity.this, "SD卡不可用，请插入SD卡",
                        Toast.LENGTH_SHORT).show();
            }
        });
        builder.setNegativeButton("取消", (dialog2, which) -> {
            ActivityController.getInstance().finishActivity();
        });
        builder.create().show();
    }

    //下载
    void downFile(final String url) {
        progressDialog = new ProgressDialog(this);    //进度条，在下载的时候实时更新进度，提高用户友好度
        progressDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setCancelable(false);
        progressDialog.setTitle("正在下载");
        progressDialog.setMessage("请稍候...");
        OkGo.post(ServerConfig.FILEDOWNLOAD + "/JTGW.apk")
                .getCall(new FileConvert(), RxAdapter.<File>create())
                .doOnSubscribe(() -> {
                    progressDialog.show();
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(file -> {
                    progressDialog.dismiss();
                    ApkUtils.install(getApplicationContext(), file);
                }, throwable -> {
                    progressDialog.dismiss();
                    throwable.printStackTrace();
                    Toast.makeText(this, "下载失败，请重试。。。", Toast.LENGTH_SHORT).show();
                });
    }
//    双击退出函数
//    在2秒内双击返回键，退出应用
    private static Boolean isExit = false;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exitBy2Click(); //调用双击退出函数
        }
        return false;
    }

    //双击方法
    private void exitBy2Click() {
        Timer tExit = null;
        if (isExit == false) {
            isExit = true; // 准备退出
            Toast.makeText(MainActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            tExit = new Timer();
            tExit.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false; // 取消退出
                }
            }, 2000); // 如果2秒钟内没有按下返回键，则启动定时器取消掉刚才执行的任务

        } else {
            MyApplication.getInstance().attemptRiZhi(SPUtils.get(getApplicationContext(), "Customerno", "").toString(), "双击返回，退出");
            ActivityController.getInstance().finishActivity();
            finish();
            System.exit(0);
        }
    }

    // 初始化 JPush。如果已经初始化，但没有登录成功，则执行重新登录。
    private void init() {
        JPushInterface.init(getApplicationContext());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mMessageReceiver);
        ButterKnife.unbind(this);
        OkGo.getInstance().cancelTag(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        isForeground = false;
        JPushInterface.onPause(this);
        OkGo.getInstance().cancelTag(this);
    }

    private MainActivity.MessageReceiver mMessageReceiver;
    public static final String MESSAGE_RECEIVED_ACTION = "com.golddaymicromall.MESSAGE_RECEIVED_ACTION";
    public static final String KEY_TITLE = "title";
    public static final String KEY_MESSAGE = "message";
    public static final String KEY_EXTRAS = "extras";

    public void registerMessageReceiver() {
        mMessageReceiver = new MainActivity.MessageReceiver();
        IntentFilter filter = new IntentFilter();
        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
        filter.addAction(MESSAGE_RECEIVED_ACTION);
        registerReceiver(mMessageReceiver, filter);
    }

    public class MessageReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {
                String messge = intent.getStringExtra(KEY_MESSAGE);
                String extras = intent.getStringExtra(KEY_EXTRAS);
                StringBuilder showMsg = new StringBuilder();
                showMsg.append(KEY_MESSAGE + " : " + messge + "\n");
                if (!JPushUtil.isEmpty(extras)) {
                    showMsg.append(KEY_EXTRAS + " : " + extras + "\n");
                }
                setCostomMsg(showMsg.toString());
            }
        }
    }

    private void setCostomMsg(String msg) {
        //设置传过来的值
    }
}
